package src.main.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.nio.charset.StandardCharsets;

/**
 * @author huwei
 */
@RestController
@CrossOrigin("*")
public class ChatController {

    @Resource
    private  ChatClient chatClient;


    @GetMapping("/chat")
    public ResponseEntity<Flux<String>> chat(@RequestParam(value = "message") String message) {
        try {
            // 调用 ChatClient 生成响应，并以 Flux<String>（响应流）形式返回
            Flux<String> chatMessage = chatClient.prompt(message).stream().content();
            Flux<String> response = chatMessage.map(item -> {
                byte[] bytes = item.getBytes(StandardCharsets.UTF_8);
                String content = new String(bytes, StandardCharsets.UTF_8);
                return content;
            });
            ResponseEntity<Flux<String>> ok = ResponseEntity.ok(response);
            return ok;
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

}
